<template>
  <div
    class="app-container"
    style="height: 100%"
    v-loading="loading"
    element-loading-text="加载中..."
  >
    <div class="back_bg" v-if="isMounted">
      <h4 class="header_top">商品管理</h4>
      <el-container class="main">
        <el-aside width="270px">
          <el-card class="box-card" style="height: 100%">
            <div class="header">
              <h4>商品类别</h4>
              <el-space :size="0" :spacer="spacer">
                <HLink @click="addLabel">新增</HLink>
                <HLink @click="editshow = !editshow" v-if="!editshow">编辑</HLink>
                <HLink @click="editshow = !editshow" v-else>完成编辑</HLink>
              </el-space>
            </div>
            <el-tree
              class="tree"
              :data="data"
              :props="defaultProps"
              default-expand-all
              node-key="id"
              highlight-current
              :current-node-key="nodeKey"
              accordion
              @node-click="handleNodeClick"
            />
            <el-tree
              class="tree"
              @node-expand="showNode"
              @node-collapse="closeNode"
              :data="data2"
              :props="defaultProps2"
              default-expand-all
              node-key="id"
              highlight-current
              :current-node-key="typeId"
              accordion
              @node-click="handleNodeClick2"
            >
              <template #default="{ node }">
                <span class="custom-tree-node">
                  <span class="label_node">{{ node.label }}</span>
                  <div v-if="editshow">
                    <el-icon
                      v-if="node.label != '全部'"
                      size="14"
                      class="show_o"
                      @click.stop="editLabel(node)"
                    >
                      <EditPen />
                    </el-icon>
                    <el-icon
                      v-if="node.label != '全部'"
                      size="14"
                      class="show_o"
                      @click.stop="remove(node)"
                    >
                      <Delete />
                    </el-icon>
                  </div>
                </span>
              </template>
            </el-tree>
            <div class="page_pages" v-if="showPage">
              <el-pagination
                hide-on-single-page
                :small="true"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="pageSize"
                :total="total"
                layout="total, prev, pager, next"
              />
            </div>
          </el-card>
        </el-aside>
        <el-main>
          <div class="list">
            <div class="btns">
              <div style="display: flex; gap: 5px; margin-bottom: 10px">
                <HPlainButton @click="addProduct"> 新增商品 </HPlainButton>
                <HPlainButton @click="onImportGoods('in')"> 导入 </HPlainButton>
                <HPlainButton @click="onImportGoods('out')"> 导出 </HPlainButton>
                <el-dropdown trigger="click">
                  <HButton :disabled="(nodeKey == 1 ? selecttio1 : selecttio2).length == 0">
                    批量操作
                    <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon>
                  </HButton>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="FactoryProduct()">
                        <el-icon>
                          <Connection />
                        </el-icon>
                        关联品牌商家
                      </el-dropdown-item>
                      <el-dropdown-item @click="changeAll(0)">
                        <el-icon>
                          <CircleCheck />
                        </el-icon>
                        批量启用
                      </el-dropdown-item>
                      <el-dropdown-item @click="changeAll(1)">
                        <el-icon>
                          <Warning />
                        </el-icon>
                        批量禁用
                      </el-dropdown-item>
                      <el-dropdown-item @click="deleAll">
                        <el-icon>
                          <Delete />
                        </el-icon>
                        批量删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="btns-right">
                <!--请选择品牌-->
                <el-select
                  style="width: 120px"
                  @change="getList"
                  @clear="getList"
                  v-model="filter.brandId"
                  placeholder="请选择品牌"
                  filterable
                  clearable
                  reserve-keyword
                  remote-show-suffix
                  :loading="brandLoading"
                  :filter-method="searchBrandSelect"
                >
                  <el-option
                    v-for="item in brandOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>

                <!--请选择来源-->
                <el-select
                  style="width: 120px"
                  @change="getList"
                  @clear="getList"
                  v-model="filter.source"
                  placeholder="请选择来源"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in sourceOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>

                <!--请选择单位-->
                <el-select
                  style="width: 120px"
                  @change="getList"
                  @clear="getList"
                  v-model="filter.unitId"
                  placeholder="请选择单位"
                  filterable
                  clearable
                  reserve-keyword
                  remote-show-suffix
                  :loading="unitLoading"
                  :filter-method="searchUnitSelect"
                >
                  <el-option
                    v-for="item in unitOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>

                <!--关联商家-->
                <el-select
                  v-if="!isParts"
                  @change="getList"
                  @clear="getList"
                  style="width: 120px"
                  v-model="filter.factory"
                  placeholder="请选择商家"
                  filterable
                  clearable
                  remote-show-suffix
                  :filter-method="handleGetFactoryOptions"
                  :loading="getFactorySelectPageLoading"
                >
                  <el-option
                    v-for="factory in factoryOptional"
                    :key="factory.id"
                    :label="factory.name"
                    :value="factory.id"
                  />
                </el-select>

                <el-input
                  style="width: 200px"
                  clearable
                  v-model="filter.keyword"
                  placeholder="请输入名称、编码、货号、型号"
                  @keyup.enter="getList"
                  @clear="getList"
                />

                <!--按钮组-->
                <div class="filter">
                  <HButton type="primary" @click="searchData">
                    <el-icon>
                      <Search />
                    </el-icon>
                    搜索
                  </HButton>
                  <HButton @click="onReset">
                    <el-icon>
                      <RefreshRight />
                    </el-icon>
                    重置
                  </HButton>
                </div>
              </div>
            </div>
            <div class="table_h">
              <el-table
                v-if="nodeKey == 1"
                style="flex: 1; position: absolute"
                ref="proTableDom"
                :border="true"
                stripe
                resizable
                :data="proTableData"
                @selection-change="handleChange1"
                @row-dblclick="doubleClick"
                height="100%"
              >
                <el-table-column type="selection" width="40" fixed />

                <!-- 序号 -->
                <el-table-column show-overflow-tooltip type="index" label="序号" width="50" fixed />
                <!-- 商品编号 -->
                <el-table-column show-overflow-tooltip prop="code" label="商品编号" width="150" />
                <!-- 商品名称 -->
                <el-table-column show-overflow-tooltip prop="name" label="商品名称" min-width="200">
                  <template #default="scope">
                    <HLink @click="doubleClick(scope.row)">
                      {{ scope.row.name }}
                    </HLink>
                  </template>
                </el-table-column>

                <!-- 状态 -->
                <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
                  <template #default="scope">
                    <HStatus v-if="!scope.row.status">启用</HStatus>
                    <HStatus v-else type="info">禁用</HStatus>
                  </template>
                </el-table-column>

                <!--关联商家-->
                <el-table-column
                  show-overflow-tooltip
                  prop="factory"
                  label="关联商家"
                  width="140"
                />

                <!-- 商品品牌 -->
                <el-table-column show-overflow-tooltip prop="brand" label="商品品牌" width="150" />

                <!-- 商品型号 -->
                <el-table-column show-overflow-tooltip prop="model" label="商品型号" width="150" />
                <!-- 商品货号 -->
                <!-- <el-table-column show-overflow-tooltip prop="itemNumber" label="商品货号" width="150" /> -->

                <!-- 商品分类 -->
                <el-table-column show-overflow-tooltip prop="type" label="商品分类" width="150" />

                <!-- 商品单位 -->
                <el-table-column show-overflow-tooltip prop="unit" label="商品单位" width="150" />

                <!-- 商品来源 -->
                <el-table-column show-overflow-tooltip prop="source" label="商品来源" width="96">
                  <template #default="scope">
                    <span>
                      {{
                        scope.row.source == 1
                          ? '系统创建'
                          : scope.row.source == 2
                          ? 'Excel导入'
                          : scope.row.source == 3
                          ? '金蝶ERP导入'
                          : '第三方接口'
                      }}
                    </span>
                  </template>
                </el-table-column>
                <!-- 创建时间 -->
                <el-table-column
                  show-overflow-tooltip
                  prop="createTime"
                  label="创建时间"
                  width="128"
                />
                <!-- 更新时间 -->
                <el-table-column
                  show-overflow-tooltip
                  prop="updateTime"
                  label="更新时间"
                  width="128"
                />
              </el-table>
              <el-table
                v-else
                ref="spareTableDom"
                style="flex: 1; position: absolute"
                height="100%"
                :border="true"
                stripe
                resizable
                :data="spareTableData"
                @selection-change="handleChange2"
                @row-dblclick="doubleClick"
              >
                <el-table-column type="selection" width="40" />
                <!-- 序号 -->
                <el-table-column show-overflow-tooltip type="index" label="序号" width="50" />
                <!-- 配件编码 -->
                <el-table-column show-overflow-tooltip prop="code" label="配件编号" width="150" />
                <!-- 配件名称 -->
                <el-table-column show-overflow-tooltip prop="name" label="配件名称" min-width="200">
                  <template #default="scope">
                    <div class="color_text" @click="doubleClick(scope.row)">
                      {{ scope.row.name }}
                    </div>
                  </template>
                </el-table-column>

                <!-- 状态 -->
                <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
                  <template #default="scope">
                    <HStatus v-if="scope.row.status === false">启用</HStatus>
                    <HStatus type="info" v-else>禁用</HStatus>
                  </template>
                </el-table-column>

                <!-- 配件品牌 -->
                <el-table-column
                  show-overflow-tooltip
                  prop="brand"
                  label="配件品牌"
                  min-width="150"
                />

                <!-- 配件型号 -->
                <el-table-column show-overflow-tooltip prop="model" label="配件型号" width="150" />

                <!-- 配件货号 -->
                <!-- <el-table-column show-overflow-tooltip prop="itemNumber" label="配件货号" width="150" /> -->

                <!-- 配件分类 -->
                <el-table-column show-overflow-tooltip prop="type" label="配件分类" width="150" />

                <!-- 配件单位 -->
                <el-table-column show-overflow-tooltip prop="unit" label="配件单位" width="150" />

                <!-- 配件来源 -->
                <el-table-column show-overflow-tooltip prop="source" label="配件来源" width="96">
                  <template #default="scope">
                    <span>
                      {{
                        scope.row.source == 1
                          ? '系统创建'
                          : scope.row.source == 2
                          ? 'Excel导入'
                          : scope.row.source == 3
                          ? '金蝶ERP导入'
                          : '第三方接口'
                      }}
                    </span>
                  </template>
                </el-table-column>

                <!-- 创建时间 -->
                <el-table-column
                  show-overflow-tooltip
                  prop="createTime"
                  label="创建时间"
                  width="128"
                />

                <!-- 更新时间 -->
                <el-table-column
                  show-overflow-tooltip
                  prop="updateTime"
                  label="更新时间"
                  width="128"
                />
              </el-table>
            </div>

            <div class="footer flex-justify-between">
              <span
                >已选中&nbsp;{{
                  nodeKey == 1 ? selecttio1.length : selecttio2.length
                }}&nbsp;条</span
              >
              <Pagination
                ref="paginationRef"
                :list_total="typeTotal"
                @size-change="getSizeList"
                @current-change="getNumList"
              />
            </div>
          </div>
        </el-main>
      </el-container>
    </div>

    <!-- 新增/修改  弹窗 -->
    <HModal v-model="dialogVisible" size="small">
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ typeDialogTitle }}</h3>
        </div>
      </template>
      <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm">
        <el-form-item label="类别名称" prop="name">
          <el-input
            clearable
            style="width: 280px"
            placeholder="请输入名称"
            v-model="ruleForm.name"
          />
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="Confirm(ruleFormRef)">确定</HButton>
        <HButton is-modal @click="dialogVisible = false"> 取消 </HButton>
      </template>
    </HModal>

    <!-- 删除弹窗 -->
    <HModal v-model="delete_dialogVisible" title="新增类别" size="small">
      您确认删除该分类？
      <template #header>
        <div class="delete_title">
          <el-icon color="rgb(255, 87, 51)" size="16">
            <WarningFilled />
          </el-icon>
          <h4>确认是否删除</h4>
        </div>
      </template>
      <template #footerRight>
        <HButton @click="deleteremove" type="primary" is-modal>确定</HButton>
        <HButton @click="delete_dialogVisible = false" is-modal> 取消 </HButton>
      </template>
    </HModal>

    <!-- 品牌关联商家-->
    <HModal v-model="FactoryProduct_show" title="品牌关联商家" size="small">
      <div>
        <!--关联商家-->
        <el-select
          v-if="!isParts"
          v-model="FactoryProductDara.factoryIds"
          placeholder="请选择商家"
          filterable
          clearable
          remote-show-suffix
          :filter-method="handleGetFactoryOptions"
          :loading="getFactorySelectPageLoading"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="2"
        >
          <el-option
            v-for="factory in factoryOptional"
            :key="factory.id"
            :label="factory.name"
            :value="factory.id"
          />
        </el-select>
      </div>
      <template #footerRight>
        <HButton @click="saveFactoryProductFun" type="primary" is-modal>确定</HButton>
        <HButton @click="FactoryProduct_show = false" is-modal> 取消 </HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
  import {
    Search,
    Delete,
    Warning,
    CircleCheck,
    ArrowDown,
    RefreshRight,
    WarningFilled,
    EditPen,
  } from '@element-plus/icons-vue'
  import type { FormInstance } from 'element-plus'
  import { ref, onMounted, reactive, watch, markRaw, computed, h } from 'vue'
  import { useRouter } from 'vue-router'
  import {
    typePageSelect,
    brandPageSelect,
    unitPageSelect,
    getProductList,
    productDisable,
    productDelete,
    getSpareList,
    SpareDisable,
    SpareDelete,
    saveFactoryProduct,
  } from '@/api/goodsInfo'
  import { typeSave, typeDelete } from '@/api/goodsSet'
  import { goodsExportExcel } from '@/api/upload'
  import moment from 'moment'
  import _ from 'lodash'
  import useGetFactoryOptionsService from '@/views/order/new/services/factorySelectPage'
  import { GetProductOrSpareListParam } from './types'
  import HLink from '@/components/common/link/HLink.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.good.goodList,
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  // 使用获取商家下拉选项服务
  const { factoryOptional, getFactorySelectPageFn, getFactorySelectPageLoading } =
    useGetFactoryOptionsService

  // 获取商家下拉选项
  const handleGetFactoryOptions = _.throttle((query: string) => {
    const param = {
      name: query,
      limit: 0,
      page: 0,
    }
    getFactorySelectPageFn(param)
  }, 500)

  const router = useRouter()
  const editshow = ref(false)
  const nodeKey = ref(1) //默认展开节点  产品
  localStorage.setItem('nodeKey', String(nodeKey.value))
  const defaultProps = {
    children: 'children',
    label: 'label',
  }

  const defaultProps2 = {
    children: 'children',
    label: 'name',
  }

  interface Tree {
    label: string
    id: number
    children?: Tree[]
  }
  const data: Tree[] = [
    { label: '成品', id: 1 },
    { label: '配件', id: 2 },
  ]
  const data2 = ref([
    {
      id: 3,
      name: '全部',
      children: [],
    },
  ])
  const delete_dialogVisible = ref(false)
  const showPage = ref(true)
  const currentPage = ref(1) // 当前页码
  const pageSize = ref(10) // 每页显示的条数
  const total = ref(0) // 总条数
  const dialogVisible = ref(false)
  const edit = ref(false)
  const loading = ref(false)

  const typeDialogTitle = ref('') // 新增/修改类别弹窗标题

  const ruleFormRef = ref()

  // 表单数据
  const ruleForm = reactive({
    id: '',
    name: '',
  })

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
  })

  const proTableDom = ref() // 商品列表Dom
  const proTableData = ref([]) // 商品列表数据

  const spareTableDom = ref() // 配件列表Dom
  const spareTableData = ref([]) // 配件列表数据

  // 商品分页Dom
  const paginationRef = ref<InstanceType<typeof Pagination> | null>(null)
  const typeTotal = ref(0) // 商品总数量

  const brandId = ref('') // 品牌ID
  const typeId = ref(3) // 商品分类ID
  const unitId = ref('') // 商品单位ID

  // 筛选
  const filter = ref<{
    factory?: string
    brandId: string
    source: string
    unitId: string
    keyword: string
  }>({
    factory: '',
    brandId: '',
    source: '',
    unitId: '',
    keyword: '',
  })

  // 获取筛选条件
  const getFilter = computed(() => {
    const result: GetProductOrSpareListParam = {
      brandId: filter.value.brandId,
      limit: 50,
      page: 1,
      source: filter.value.source,
      typeId: typeId.value == 3 ? '' : typeId.value,
      unitId: filter.value.unitId,
      keyword: filter.value.keyword,
      factoryId: filter.value.factory,
    }

    if (isParts.value) {
      delete result.factoryId
    }

    if (paginationRef.value) {
      result.limit = paginationRef.value.size
      result.page = paginationRef.value.current
    }

    return result
  })

  // 当前节点是否为配件
  const isParts = ref(false)

  // 点击节点时
  const handleNodeClick = (data: Tree) => {
    nodeKey.value = data.id
    localStorage.setItem('nodeKey', String(nodeKey.value))
    if (data.id === 1) {
      isParts.value = false
      getProductData()
    } else {
      isParts.value = true
      getSpareData()
    }
  }

  /**
   * 重置事件
   */
  const onReset = () => {
    filter.value = {
      keyword: '',
      brandId: '',
      unitId: '',
      source: '',
      factory: '',
    }
    if (isParts.value) {
      getSpareData()
    } else {
      getProductData()
    }
  }
  const getList = () => {
    if (nodeKey.value === 1) {
      getProductData()
    } else {
      getSpareData()
    }
  }

  /**
   * 获取产品列表
   */
  const getProductData = async () => {
    loading.value = true
    const res = await getProductList(getFilter.value)
    proTableData.value = res.data.data.rows
    typeTotal.value = Number(res.data.data.total)
    loading.value = false
  }

  /**
   * 获取配件列表
   */
  const getSpareData = async () => {
    loading.value = true
    const res = await getSpareList(getFilter.value)
    spareTableData.value = res.data.data.rows
    typeTotal.value = Number(res.data.data.total)
    loading.value = false
  }

  const unitLoading = ref(false)
  const brandLoading = ref(false)

  const brandVal = ref()
  const searchUnit = ref('')

  // 搜索框下拉数据
  const brandOptions = ref([])
  const unitOptions = ref([])
  const sourceOptions = ref([
    {
      id: '1',
      name: '系统创建',
    },
    {
      id: '2',
      name: 'Excel导入',
    },
    {
      id: '3',
      name: '金蝶ERP导入',
    },
    {
      id: '4',
      name: '第三方接口',
    },
  ])

  // 获取商品类型
  const getTypeData = async () => {
    loading.value = true
    const data = {
      limit: pageSize.value,
      name: '',
      page: currentPage.value,
    }
    const res = await typePageSelect(data)
    data2.value[0].children = res.data.data.rows
    total.value = Number(res.data.data.total)
    loading.value = false
  }

  // 搜索品牌下拉数据
  const searchBrandSelect = _.throttle((query: string) => {
    if (brandVal.value !== query) {
      brandVal.value = query
      getBrandOptions(brandVal.value)
    }
  }, 500)

  // 获取品牌下拉数据
  const getBrandOptions = async (name: string) => {
    brandLoading.value = true
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await brandPageSelect(data)
    brandOptions.value = res.data.data.rows
    brandLoading.value = false
  }

  const searchUnitSelect = _.throttle((val) => {
    if (searchUnit.value !== val) {
      searchUnit.value = val
      getUnitOptions(searchUnit.value)
    }
  }, 500)

  // 获取单位下拉数据
  const getUnitOptions = async (name: string) => {
    unitLoading.value = true
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    const res = await unitPageSelect(data)
    unitOptions.value = res.data.data.rows
    unitLoading.value = false
  }

  const handleNodeClick2 = (data: Tree) => {
    typeId.value = data.id
    if (nodeKey.value == 1) {
      getProductData()
    } else {
      getSpareData()
    }
  }

  // 新增类别
  const addLabel = () => {
    typeDialogTitle.value = '添加类别'
    dialogVisible.value = true
    ruleForm.name = ''
    edit.value = false
  }

  // current-page 改变时触发
  const handleCurrentChange = (page: number) => {
    currentPage.value = page
    getTypeData()
  }

  // 节点展开时触发
  const showNode = (data: Tree) => {
    if (data.id == 3) {
      showPage.value = true
    }
  }

  // 节点关闭时触发
  const closeNode = (data: Tree) => {
    if (data.id == 3) {
      showPage.value = false
    }
  }

  const onImportGoods = async (str) => {
    if (proTableData.value.length == 0 && nodeKey.value == 1) {
      ElMessage({
        type: 'warning',
        message: '暂无数据导出',
      })
      return
    }
    if (spareTableData.value.length == 0 && nodeKey.value == 2) {
      ElMessage({
        type: 'warning',
        message: '暂无数据导出',
      })
      return
    }
    loading.value = true
    if (str === 'out') {
      const res = await goodsExportExcel(getFilter.value, nodeKey.value)
      if (res.data.isError)
        ElMessage({
          type: res.data.code && !res.data.success ? 'error' : 'success',
          message: res.data.code && !res.data.success ? res.data.message : '商品资料数据导出成功',
        })
      if (res.data.code && !res.data.success) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
      const link = document.createElement('a')
      link.href = url
      link.download = `商品资料_${moment(new Date()).format('YYYYMMDD')}.xlsx`
      link.click()
    } else if (str === 'in') {
      router.push({ path: 'goodsExcelImport', query: { type: nodeKey.value } })
    }
    loading.value = false
  }

  // 新增商品
  const addProduct = () => {
    if (nodeKey.value == 1) {
      router.push({ path: '/commodity/commodi/1' })
      return
    }
    if (nodeKey.value == 2) {
      router.push({ path: '/commodity/commodi/2' })
      return
    }
  }

  // 新增or修改商品类别 确定
  const Confirm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    const data = {
      name: ruleForm.name,
      status: false,
    }
    const data2 = {
      id: ruleForm.id,
      name: ruleForm.name,
      status: false,
    }
    formEl.validate((valid) => {
      if (valid) {
        if (typeDialogTitle.value == '添加类别') {
          saveTypeData(data, typeSave, dialogVisible, getTypeData)
        } else {
          saveTypeData(data2, typeSave, dialogVisible, getTypeData)
        }
      } else {
        return
      }
    })
  }

  // 删除节点
  const remove = (node: { data: { id: any } }) => {
    ruleForm.id = node.data.id
    delete_dialogVisible.value = true
  }

  // 确认删除节点
  const deleteremove = () => {
    typeDelete([ruleForm.id]).then((res) => {
      ElMessage({
        message: res.data.message,
        type: 'success',
        duration: 2000,
      })
      delete_dialogVisible.value = false
      getTypeData()
    })
  }

  // 商品详情
  const doubleClick = (val) => {
    if (nodeKey.value == 1) {
      router.push({ path: '/commodity/commodi/detail/' + val.id })
      return
    }
    if (nodeKey.value == 2) {
      router.push({ path: '/commodity/commodi/detail/' + val.id })
      return
    }
  }

  // 编辑类别
  const editLabel = (node) => {
    typeDialogTitle.value = '编辑类别'
    ruleForm.name = node.data.name
    ruleForm.id = node.data.id
    dialogVisible.value = true
    edit.value = true
  }
  // 搜索商品/配件
  const searchData = () => {
    if (nodeKey.value == 1) {
      getProductData()
    } else {
      getSpareData()
    }
  }

  // 获取表格选中的数据   1-商品 2-配件
  const selecttio1 = ref([])
  const selecttio2 = ref([])
  const handleChange1 = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttio1.value).indexOf(item.id) == -1) {
          selecttio1.value.push(item.id)
        } else {
          selecttio1.value = selecttio1.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttio1.value = []
    }
  }
  const handleChange2 = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttio2.value).indexOf(item.id) == -1) {
          selecttio2.value.push(item.id)
        } else {
          selecttio2.value = selecttio2.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttio2.value = []
    }
  }

  // 封装修改状态的方法
  const changeDisable = (type, name, method, arr, status, dom) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的${name}`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的${name}?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != '3') {
        // 批量启用/禁用
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        })
      } else {
        // 批量删除
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        })
      }
      dom.clearSelection()
      if (name == '商品') {
        getProductData()
      } else {
        getSpareData()
      }
    })
  }

  // 批量启用/禁用
  const changeAll = (n: number) => {
    if (n == 1) {
      if (nodeKey.value == 1) {
        changeDisable('禁用', '商品', productDisable, selecttio1.value, true, proTableDom.value)
      } else {
        changeDisable('禁用', '配件', SpareDisable, selecttio2.value, true, spareTableDom.value)
      }
    } else {
      if (nodeKey.value == 1) {
        changeDisable('启用', '商品', productDisable, selecttio1.value, false, proTableDom.value)
      } else {
        changeDisable('禁用', '配件', SpareDisable, selecttio2.value, false, spareTableDom.value)
      }
    }
  }

  // 批量删除
  const deleAll = () => {
    if (nodeKey.value == 1) {
      changeDisable('删除', '商品', productDelete, selecttio1.value, '3', proTableDom.value)
    } else {
      changeDisable('删除', '配件', SpareDelete, selecttio2.value, '3', spareTableDom.value)
    }
  }

  const FactoryProductDara = ref({
    factoryIds: [], //	品牌商家ID
    productIds: [], //商品ID
  })
  const FactoryProduct_show = ref(false)
  // 关联品牌商家
  const FactoryProduct = () => {
    FactoryProduct_show.value = true
  }
  // 保存
  const saveFactoryProductFun = () => {
    if (FactoryProductDara.value.factoryIds.length == 0) {
      ElMessage({
        message: '请选择关联商家',
        type: 'warning',
        duration: 2000,
      })
      return
    }
    FactoryProductDara.value.productIds = selecttio1.value
    saveFactoryProduct(FactoryProductDara.value).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        FactoryProductDara.value.factoryIds = []
        FactoryProductDara.value.productIds = []
        FactoryProduct_show.value = false
        getSizeList()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        return
      }
    })
  }
  // 封装保存数据的方法
  const saveTypeData = async (data, method, dialog, getData) => {
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        dialog.value = false
        getData()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        return
      }
    })
  }

  // 分页改变时
  const getSizeList = () => {
    if (nodeKey.value == 1) {
      getProductData()
    } else {
      getSpareData()
    }
  }
  // 页码改变时
  const getNumList = () => {
    if (nodeKey.value == 1) {
      getProductData()
    } else {
      getSpareData()
    }
  }

  // 成品、配件替换
  watch(nodeKey, () => {
    selecttio1.value = []
    selecttio2.value = []
  })
  const isMounted = ref(false)
  onMounted(() => {
    isMounted.value = true
    getTypeData()
    getBrandOptions(brandId.value)
    getUnitOptions(unitId.value)
    getProductData()
  })
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
